package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.检查参数
        dto.checkParam();

        //2.分页条件查询

        IPage page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //按照用户查询
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());

        //发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);

        page = page(page, lambdaQueryWrapper);
        List<WmNews> records = page.getRecords();
        List<Integer> userIds = new ArrayList<>();
        for (WmNews record : records) {
            userIds.add(record.getUserId());
        }
        List<WmUser> wmUsers = wmUserMapper.selectList(Wrappers.<WmUser>lambdaQuery().in(WmUser::getId, userIds));

        List<WmNewsName> wmNewsNames = new ArrayList<>();
        for (WmNews wmNews : records) {
            for (WmUser wmUser : wmUsers) {
                if(wmNews.getUserId()==wmUser.getId()){
                    WmNewsName wmNewsName = new WmNewsName();
                    BeanUtils.copyProperties(wmNews,wmNewsName);
                    wmNewsName.setName(wmUser.getName());
                    wmNewsNames.add(wmNewsName);
                    break;
                }
            }
        }

        //3.返回，分页
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(wmNewsNames);
        return responseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 提交待审核、修改、保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.校验参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存或修改文章
        WmNews wmNews = saveOrUpdateNews(dto);

        //3.如果状态为0，是草稿，结束方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //提取文章内容中的图片列表
        List<String> materials = ectractUrlInfo(dto.getContent());

        //4.如果状态为1  待审核，保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());


        //5.如果状态为1  待审核，保存文章封面图片与素材的关系,如果封面类型是自动，需匹配封面
        saveRelativeInfoForCover(wmNews, materials, dto);

        //添加到延迟任务
        wmNewsTaskService.addNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 1,如果封面类型是自动，需匹配封面
     * 匹配规则：
     * 内容图片大于等于1  小于3  单图  type:1
     * 内容图片大于等于3  多图  type:3
     * 内容没有图片  无图  type:0
     * 2，保存文章封面图片与素材的关系
     *
     * @param wmNews
     * @param materials
     * @param dto
     */
    private void saveRelativeInfoForCover(WmNews wmNews, List<String> materials, WmNewsDto dto) {

        //前台传递过来的封面图片
        List<String> images = dto.getImages();

        //如果封面类型是自动，需匹配封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = materials.size();
            if (size >= 1 && size < 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else if(size >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if(images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);

        }
        //保存文章封面图片与素材的关系
        if(images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }

    /**
     * 保存文章内容图片与素材的关系
     *
     * @param materials
     * @param id
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        saveRelativeInfo(materials, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章图片与素材的关系到数据库
     *
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {

        if (materials != null && materials.size() > 0) {

            //去重
            materials = materials.stream().distinct().collect(Collectors.toList());

            //获取素材信息
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

            //假如说，当前文章之前是草稿，现在修改为待审核，图片被删除过---》素材引用失效
            if (dbMaterials == null || dbMaterials.size() == 0 || materials.size() != dbMaterials.size()) {
                //手动抛出异常，作用有两个  第一：保证事务一致，第二，提示用户
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }


            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            /*List<Integer> idList = new ArrayList<>();
            for (WmMaterial dbMaterial : dbMaterials) {
                idList.add(dbMaterial.getId());
            }*/
            wmNewsMaterialMapper.saveRelations(idList, newsId, type);
        }


    }

    /**
     * 提取文章内容中的图片列表
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {

        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                materials.add((String) map.get("value"));
            }
        }
        return materials;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     *
     * @param dto
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //封面图片，单独处理
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //[123.jpg,2345.jpg]-->123.jpg,2345.jpg
//            dto.getImages().toString().replaceAll("]","").replaceAll("[","")
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagesStr);
        }

        //如果封面类型选择的是自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        //补充其他字段
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());

        if (dto.getId() == null) {
            //保存
            save(wmNews);
        } else {

            //删除素材与文章的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));

            //修改
            updateById(wmNews);

        }
        return wmNews;
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        System.out.println("git冲突");

        //1.检验参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.是否是已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章没有发布，不能上下架");
        }

        //4.修改文章
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){

            /*wmNews.setEnable(dto.getEnable());
            updateById(wmNews);*/

            //update wmnews set enable = ? where id = ?
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,wmNews.getId())
                    .set(WmNews::getEnable,dto.getEnable()));

            if(wmNews.getArticleId() != null){
                Map<String,Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",dto.getEnable());
                //发送消息
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询自媒体文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult detailsQuery(Integer id) {
        //查询文章信息
        WmNews wmNews = getById(id);
        //查询作者信息
        WmUser wmUser = null;//提升作用域
        if(wmNews != null && wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //封装信息返回
        WmNewsName wmNewsName = new WmNewsName();
        BeanUtils.copyProperties(wmNews,wmNewsName);
        if( wmUser!= null){
            wmNewsName.setName(wmUser.getName());
        }
        return ResponseResult.okResult(wmNewsName);
    }

    /**
     * 审核成功还是失败
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult yesOrNo(Integer id,Integer type,String reason) {
        //查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(type.equals(0)){
            wmNews.setStatus((short) 2);
            wmNews.setReason(reason);
            updateById(wmNews);
        }else if (type.equals(1)){
            wmNews.setStatus((short) 4);
            wmNews.setReason("审核成功");
            updateById(wmNews);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
